import os
import subprocess

class VideoToGIF:
    def __init__(self, input_path=None, output_path=r"C:\Users\33720\Desktop\output.gif"):
        self.input_path = input_path
        self.output_path = output_path

        # 默认参数
        self.start_time = 0         # GIF 起始时间（秒）
        self.duration = None        # 持续时间（秒）
        self.fps = 10               # 帧率
        self.width = None           # 输出宽度，保持比例缩放
        self.height = None          # 输出高度，保持比例缩放
        self.loop = 0               # 循环次数 0 = 无限循环

    # Setter 方法
    def set_input_path(self, path):
        self.input_path = path

    def set_output_path(self, path):
        self.output_path = path

    def set_start_time(self, seconds):
        self.start_time = seconds

    def set_duration(self, seconds):
        self.duration = seconds

    def set_fps(self, fps):
        self.fps = fps

    def set_size(self, width=None, height=None):
        self.width = width
        self.height = height

    def set_loop(self, loop):
        self.loop = loop

    def generate_gif(self):
        if not self.input_path or not os.path.isfile(self.input_path):
            print(f"❌ 输入文件不存在: {self.input_path}")
            return

        if not self.output_path:
            base_name = os.path.splitext(os.path.basename(self.input_path))[0]
            self.output_path = os.path.join(os.path.dirname(self.input_path), f"{base_name}.gif")

        # 构建 ffmpeg 命令
        cmd = ['ffmpeg', '-y', '-i', self.input_path]

        # 起始时间
        if self.start_time > 0:
            cmd += ['-ss', str(self.start_time)]

        # 持续时间
        if self.duration:
            cmd += ['-t', str(self.duration)]

        # 帧率
        cmd += ['-r', str(self.fps)]

        # 缩放
        if self.width and self.height:
            cmd += ['-vf', f'scale={self.width}:{self.height}:flags=lanczos']
        elif self.width:
            cmd += ['-vf', f'scale={self.width}:-1:flags=lanczos']
        elif self.height:
            cmd += ['-vf', f'scale=-1:{self.height}:flags=lanczos']

        # 循环
        cmd += ['-loop', str(self.loop), self.output_path]

        print(f"✨ 正在生成 GIF: {self.output_path}")
        subprocess.run(cmd, check=True)
        print("✅ GIF 生成完成！")


# 使用示例
if __name__ == "__main__":
    converter = VideoToGIF()
    converter.set_input_path(r"C:\Users\33720\Desktop\12.mp4")
    converter.set_start_time(4)     # 从视频第5秒开始
    converter.set_duration(15)       # 持续3秒
    converter.set_fps(20)           # 帧率15
    converter.set_size(width=320)   # 宽度320，按比例缩放高度
    converter.set_loop(0)           # 无限循环

    converter.generate_gif()
